#include "table.h"

#include <jni.h>

#include <stddef.h>

#include <stdio.h>

#include <string.h>

#include "sqlite3.h"

#include "tags.h"

#include "log/log.h"

static int table_init_exec(sqlite3* db, const char* exec, const char* sql) {
	sqlite3_stmt* statement = NULL;
	int ret = sqlite3_prepare_v2(db, sql, -1, &statement, 0);

//	log_print(ANDROID_LOG_DEBUG, TAG_NIM_INDEX_OP, "table_init_%s : prepare %d", exec, ret);

	if (ret != SQLITE_OK) {
		return ret;
	}

	ret = sqlite3_step(statement);
//	log_print(ANDROID_LOG_DEBUG, TAG_NIM_INDEX_OP, "table_init_%s : step %d", exec, ret);

	sqlite3_finalize(statement);

	return ret;
}

#define CREATE_INDEX_SQL "CREATE VIRTUAL TABLE IF NOT EXISTS FtsIndexMessage USING fts4(content, tokenize=nim);"

#define CREATE_META_SQL "CREATE TABLE IF NOT EXISTS FtsMetaMessage (" \
		"docid INTEGER PRIMARY KEY, " \
		"type LONG, " \
		"subtype LONG DEFAULT 0, " \
		"dataid LONG, " \
		"id TEXT, " \
		"time LONG, " \
		"status INT DEFAULT 0" \
		");"

#define CREATE_META_INDEX_ID_SQL "CREATE INDEX IF NOT EXISTS FtsMetaMessage_id ON FtsMetaMessage(id);"

#define CREATE_META_INDEX_ID_TIME_SQL "CREATE INDEX IF NOT EXISTS FtsMetaMessage_id_time ON FtsMetaMessage(id, time);"

#define CREATE_META_INDEX_TYPE_DATAID_SQL "CREATE INDEX IF NOT EXISTS FtsMetaMessage_type_dataid ON FtsMetaMessage(type, dataid);"

int table_init(sqlite3* db) {
	int ret = table_init_exec(db, "index", CREATE_INDEX_SQL);
	if (ret != SQLITE_DONE) {
		return ret;
	}

	ret = table_init_exec(db, "meta", CREATE_META_SQL);
	if (ret != SQLITE_DONE) {
		return ret;
	}

	ret = table_init_exec(db, "meta_index_id", CREATE_META_INDEX_ID_SQL);
	if (ret != SQLITE_DONE) {
		return ret;
	}

	ret = table_init_exec(db, "meta_index_id_time", CREATE_META_INDEX_ID_TIME_SQL);
	if (ret != SQLITE_DONE) {
		return ret;
	}

	ret = table_init_exec(db, "meta_index_type_dataid", CREATE_META_INDEX_TYPE_DATAID_SQL);

	return ret;
}
